package com.xuan.api.account.controller;

import com.xuan.api.account.service.AccountRemoteApiService;
import com.xuan.model.entity.User;
import com.xuan.model.respons.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 验证与跳转Servlet
 */
@Controller
@RequestMapping("/account")
@Slf4j
public class AccountController {

    @Autowired
    private AccountRemoteApiService accountRemoteApiService;

    @RequestMapping("/index")
    public String index() {//跳板
        return "index";
    }

    @GetMapping("login/{username}/{password}")
    @ResponseBody
    public ResultBody login(@PathVariable("username") String username, @PathVariable("password") String password, HttpServletResponse response) {

        log.info("username==="+username+"password===="+password);
        User user = new User();

        if (StringUtils.isNotBlank(username)){
            user.setUsername(username);
        }
        if (StringUtils.isNotBlank(password)){
            user.setPwd(password);
        }


        Map result = accountRemoteApiService.login(user);
        if (result.containsKey("AccountInfo")){
            response.addHeader("AccountInfo", (String) result.get("AccountInfo"));
            return new ResultBody().OK();
        }
        return new ResultBody().Fail();

    }

    @RequestMapping("/main")
    public String main(){
        return "reset";
    }

    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    @RequestMapping("/index2")
    public String index2(){
        return "index2";
    }

    @RequestMapping("/update")
    public String update(@RequestParam("username") String username, Model model){
        log.info(username);
        User user = accountRemoteApiService.findOne(username);
        model.addAttribute("user",user);
        return "update";
    }

    @ResponseBody
    @PostMapping("/update")
    public ResultBody updateRoles(@RequestBody User user){
        return accountRemoteApiService.updateRoles(user);
    }

    @RequestMapping("/reset")
    public String resetPassword(){
        return "reset";
    }
}
